<template>
  <div class="app-container">
    <el-card class="table-card">
      <div slot="header" class="clearfix">
        <toolbar :config="toolbarConfig" @dialog="showDialog" />
      </div>
      <div class="table-container">
        <el-table v-el-height-adaptive-table="{bottomOffset: 88}" v-loading="tableLoading" :data="tableData" border size="mini" width="100%" height="100px">
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column prop="name" align="center" label="名称" width="180" />
          <el-table-column prop="display_name" align="center" label="显示名称" />
          <el-table-column prop="status" align="center" label="状态">
            <template slot-scope="{row}">
              <el-tag :type="row.status | statusTagFilter" size="mini">
                {{ row.status | statusTextFilter }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" align="center" label="创建时间" />
          <el-table-column prop="updated_at" align="center" label="更新时间" />
          <el-table-column align="center" label="操作" width="400">
            <template slot-scope="{row}">
              <el-button type="text" size="mini" @click="edit(row)">
                编辑
              </el-button>
              <el-button v-if="row.status!=='deleted'" size="mini" type="text" @click="del(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
      />
    </el-card>
    <el-dialog
      :title="dialogTitle"
      width="30%"
      class="dialog"
      :visible.sync="dialogVisible">
      <el-form ref="form" :model="form" :rules="rules" :validate-on-rule-change="false" label-width="90px" size="small">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="显示名称" prop="display_name">
          <el-input v-model="form.display_name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="权限列表" prop="permissions">
          <el-tree
            ref="tree"
            v-loading="permissionLoading"
            :data="permissionData"
            :props="defaultProps"
            :default-checked-keys="form.permissions"
            node-key="id"
            show-checkbox
            class="permission-tree"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" size="mini">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Toolbar from '@/components/Toolbar'
import Pagination from '@/components/Pagination'
import { array2tree, deepClone } from '@/utils'
import { getRoleList, getPermissionList, createRole, updateRole, destroyRole } from '@/api/system/role'
import elHeightAdaptiveTable from '@/directive/el-table'

export default {
  components: {
    Toolbar,
    Pagination
  },
  directives: { elHeightAdaptiveTable },
  data() {
    return {
      toolbarConfig: [],
      tableLoading: true,
      permissionLoading: true,
      tableData: [],
      dialogVisible: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogTitle: '',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'display_name'
      },
      permissionData: [],
      form: {
        name: '',
        display_name: '',
        permissions: [],
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: ['blur', 'change'] },
          { type: 'string', max: 191, message: '名称最大长度为191', trigger: 'blur' }
        ],
        display_name: [
          { type: 'string', required: true, message: '请输入显示名称', trigger: ['blur', 'change'] },
          { max: 191, message: '显示名称名称最大长度为191', trigger: 'blur' }
        ],
        status: [
          { type: 'enum', message: '请选择状态', trigger: 'blur', enum: [0, 1] }
        ]
      }
    }
  },
  watch: {
    dialogVisible(newVal) {
      if (newVal && this.permissionData.length === 0) {
        this.getPermissionList()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getRoleList().then(response => {
        const { code, data, message } = response
        if (code === 1) {
          this.tableData = data.list
          this.currentPage = data.meta.current_page
          this.pageSize = data.meta.per_page
          this.total = data.meta.total
          this.toolbarConfig = data.permissions
        } else {
          this.$message({
            message: message || 'Error',
            type: 'error'
          })
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    getPermissionList() {
      getPermissionList().then(response => {
        const { code, data, message } = response
        if (code === 1) {
          this.permissionData = array2tree(deepClone(data))
        } else {
          this.$message({
            message: message || 'Error',
            type: 'error'
          })
        }
        this.permissionLoading = false
      }).catch(() => {
        this.permissionLoading = false
      })
    },
    showDialog(event, text, type) {
      if (event === 'add') {
        this.create(text)
      } else if (event === 'del') {
        this.del()
      }
    },
    create(text) {
      this.dialogTitle = text + '角色'
      if (this.$refs['form'] !== undefined) {
        this.$refs.form.resetFields()
      }
      this.form = { status: 1, permissions: [] }
      if (this.permissionData.length > 0) {
        // 清空
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys([])
        })
      }
      this.dialogVisible = true
    },
    edit(row) {
      this.dialogTitle = '编辑角色'
      this.form = deepClone(row)
      this.dialogVisible = true
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.permissions = this.$refs.tree.getCheckedKeys()
          if (!this.form.id) {
            createRole(this.form).then(response => {
              const { code, data, message } = response
              if (code === 1) {
                this.tableData.unshift(data)
              } else {
                this.$message({
                  message: message || 'Error',
                  type: 'error'
                })
              }
            }).catch(() => {
            })
          } else {
            updateRole(this.form).then(response => {
              const { code, data, message } = response
              if (code === 1) {
                const index = this.tableData.findIndex(item => {
                  return item.id === data.id
                })
                this.$set(this.tableData, index, data)
              } else {
                this.$message({
                  message: message || 'Error',
                  type: 'error'
                })
              }
            }).catch(() => {
            })
          }
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    del(row) {
      destroyRole(row).then(response => {
        let message_type = 'error'
        const { code, message } = response
        if (code === 1) {
          const index = this.tableData.findIndex(item => {
            return item.id === row.id
          })
          this.tableData.splice(index, 1)
          message_type = 'success'
        }
        this.$message({
          message: message,
          type: message_type
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
